<template>
    <div>
        <!-- 权限树 -->
        <a-tree
            :checkable = "true"
            :expandedKeys="expandedKeys"
            :autoExpandParent="autoExpandParent"
            v-model="checkedKeys"
            :treeData="dataSource"
            @expand="keys => {
                this.expandedKeys = keys;
                this.autoExpandParent = false;
            }"
            @check="keys => this.checkedKeys = keys"
        />
        <br />
        <a-button type="primary" @click="onSubmit" block>提交</a-button>
    </div>
</template>

<script>
    import { getSysMenuTree,getRoleAuthorities,editAuthorities } from '../../../apis/upms';
    export default {
        data(){
            return {
                roleId : undefined,
                expandedKeys : [],  //  默认展开指定的树节点
                autoExpandParent: true, //  是否自动展开父节点
                checkedKeys : [],   //  选中的Keys
                dataSource : []   //  数据源
            };
        },
        created(){
            let $this = this;
            // 根据Id获取角色信息
            $this.roleId = $this.$route.params['roleId'];
            getSysMenuTree().then(result => {
                //  格式化数据
                $this.dataSource = $this.createTreeData(result.data);
                getRoleAuthorities($this.roleId).then(res => {
                    $this.checkedKeys = res.data;
                    $this.expandedKeys = res.data;
                });
            });
        },
        methods : {
            /**
             * 递归创建符合Tree组件规范的数据
             * @param dataList 数据列表
             * @returns {[]}
             */
            createTreeData : function(dataList) {
                let list = [];
                dataList.forEach(data => {
                    let item = {
                        key : data['id'],
                        title : data['name']
                    };
                    let children = data['children'];
                    if (children && children instanceof Array){
                        item.children = this.createTreeData(children);
                    }
                    list.push(item);
                });
                return list;
            },
            onSubmit : function () {
                let $this = this;
                editAuthorities({ id : $this.roleId, menuIdList : $this.checkedKeys }).then(() => {
                    $this.$message.success("保存成功").then();
                    $this.$router.push({ name : 'sysRoleManage' }).then();
                })
            }
        }
    }
</script>
